package com.wzw.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XMLUtil {

	private String rootNode = "root";
	
	private String outFile = "";
	
	private Document document;
	
	private Element rootElement;
	
	private OutputFormat format;
	
	private FileWriter fileWriter;
	
	private XMLWriter write;
	
	public XMLUtil() {
		this.document = DocumentHelper.createDocument();
		this.format = new OutputFormat("  ", true, "UTF-8");
	}
	
	public XMLUtil(String rootNodeName) {
		this.document = DocumentHelper.createDocument();
		this.format = new OutputFormat("  ", true, "UTF-8");
		rootElement = document.addElement(rootNodeName);
	}
	
	public Element addElements(String attribute) {
		if(null == rootElement) {
			rootElement = document.addElement(rootNode);
		}
		return rootElement.addElement(attribute);
	}
	
	public void writeToXMLFile() {
		try {
			fileWriter = new FileWriter(outFile);
			write = new XMLWriter(fileWriter, format);
			write.write(document);
			write.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String docToString() {
		return document.asXML();
	}

	public String getRootNode() {
		return rootNode;
	}

	public void setRootNode(String rootNode) {
		this.rootNode = rootNode;
	}

	public String getOutFile() {
		return outFile;
	}

	public void setOutFile(String outFile) {
		this.outFile = outFile;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public Element getRootElement() {
		return rootElement;
	}

	public void setRootElement(Element rootElement) {
		this.rootElement = rootElement;
	}

	public OutputFormat getFormat() {
		return format;
	}

	public void setFormat(OutputFormat format) {
		this.format = format;
	}

	public FileWriter getFileWriter() {
		return fileWriter;
	}

	public void setFileWriter(FileWriter fileWriter) {
		this.fileWriter = fileWriter;
	}

	public XMLWriter getWrite() {
		return write;
	}

	public void setWrite(XMLWriter write) {
		this.write = write;
	}
	
}
